<?php

namespace App\Http\Controllers\Console\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Tenant\TenantMenu;
use App\Models\Tenant\TenantPriv;
use Illuminate\Http\Request;
use DB;
use Validator;
use Illuminate\Support\Facades\Redis;

class TenantMenuController extends Controller
{
    // 取下拉框菜单
    public function getSelect()
    {
        try {
            $menus = TenantMenu::select('id', 'parentid', 'name', 'sort', 'url')->orderBy('sort', 'asc')->get();
            $res = [];
            $f_menus = $menus->where('parentid', 0)->all();
            // 只查三级
            foreach ($f_menus as $v) {
                // 一级
                $res[] = ['label' => $v->name, 'value' => $v->id];
                // 二级
                $s_menus = $menus->where('parentid', $v->id)->all();
                foreach ($s_menus as $s) {
                    $res[] = ['label' => '|- ' . $s->name, 'value' => $s->id];
                    // 三级的
                    $t_menus = $menus->where('parentid', $s->id)->all();
                    foreach ($t_menus as $t) {
                        $res[] = ['label' => '||- ' . $t->name, 'value' => $t->id];
                    }
                }
            }
            return $this->resData(200, '获取成功...', $res);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取失败，请稍后再试...');
        }
    }
    // 取左侧权限菜单
    public function getList(Request $req)
    {
        try {
            // 一级菜单
            $all = TenantMenu::select('id', 'parentid', 'name', 'url', 'icon', 'label')->where('display', '=', '1')->orderBy('sort', 'asc')->orderBy('id', 'asc')->get();
            $leftmenu = array();
            // 判断权限
            $left = $all->where('parentid', 0)->all();
            // 取到用户信息
            $token = $req->header('Authorization');
            $token_info = Redis::get('c-token:' . $token);
            // 解析用户信息，判断权限
            $user = json_decode($token_info);
            // 判断权限
            if (!in_array(1, $user->allRole)) {
                foreach ($left as $k => $v) {
                    foreach ($user->allPriv as $url) {
                        if ($v['label'] == $url) {
                            $leftmenu[$k] = $v;
                        }
                    }
                }
            } else {
                $leftmenu = $left;
            }
            // 二级菜单
            foreach ($leftmenu as $k => $v) {
                // 取所有下级菜单
                $submenu = $all->where('parentid', '=', $v['id'])->all();
                // 进行权限判断
                if (!in_array(1, $user->allRole)) {
                    $childSubMenu = [];
                    foreach ($submenu as $s => $v) {
                        if (in_array($v['label'], (array) $user->allPriv)) {
                            $childSubMenu[$s] = $v;
                        }
                    }
                    $leftmenu[$k]['submenu'] = $childSubMenu;
                } else {
                    $leftmenu[$k]['submenu'] = $submenu;
                }
            }
            // return $this->resData(200, '获取成功...', $leftmenu);
            // 三级菜单
            foreach ($leftmenu as $k => $v) {
                $submenu = $v['submenu'];
                // 所有二级
                foreach ($submenu as $s => $sub) {
                    // 取所有下级菜单
                    $there = $all->where('parentid', '=', $sub['id'])->all();
                    // 进行权限判断
                    if (!in_array(1, $user->allRole)) {
                        $thereSubMenu = [];
                        foreach ($there as $t => $v) {
                            if (in_array($v['label'], (array) $user->allPriv)) {
                                $thereSubMenu[$t] = $v;
                            }
                        }
                        $submenu[$s]['there'] = $thereSubMenu;
                    } else {
                        $submenu[$s]['there'] = $there;
                    }
                }
                $leftmenu[$k]['submenu'] = $submenu;
            }
            return $this->resData(200, '获取成功...', $leftmenu);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取失败，请稍后再试...');
        }
    }
    // 查出所有有权限的url
    private function allPriv()
    {
        $rid = session('console')->allRole;
        // 查url
        $priv = TenantPriv::whereIn('role_id', $rid)->pluck('url')->toArray();
        return $priv;
    }
    // 取菜单树
    public function getTree()
    {
        try {
            // 所有菜单
            $all = TenantMenu::select('id', 'parentid', 'name', 'url', 'display', 'sort')->orderBy('sort', 'asc')->orderBy('id', 'asc')->get();
            $tree = $this->toTree($all, 0);
            return $this->resData(200, '获取成功...', $tree);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取失败，请稍后再试...');
        }
    }
    // 转成树形菜单数组
    private function toTree($data, $pid)
    {
        $tree = [];
        if ($data->count() > 0) {
            foreach ($data as $v) {
                if ($v->parentid == $pid) {
                    $v = ['menu_id' => $v->id, 'title' => $v->name, 'sort' => $v->sort, 'display' => $v->display, '_showChildren' => true];
                    $v['children'] = $this->toTree($data, $v['menu_id']);
                    $tree[] = $v;
                }
            }
        }
        return $tree;
    }
    // 添加菜单
    public function postCreate(Request $req)
    {
        DB::beginTransaction();
        try {
            $validator = Validator::make($req->input(), [
                'parentid' => 'required|integer',
                'name' => 'required|max:255',
                'url' => 'required|max:255',
                'label' => 'required|max:255',
                'display' => 'required|in:true,false',
            ]);
            $attrs = array(
                'parentid' => '父级菜单',
                'name' => '菜单名称',
                'url' => '菜单名称',
                'label' => '菜单标签',
                'display' => '状态',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $insert = ['parentid' => $req->input('parentid', 0), 'name' => $req->input('name'), 'url' => $req->input('url'), 'label' => $req->input('label'), 'icon' => $req->input('icon'), 'display' => $req->input('display') == 'true' ? 1 : 0, 'sort' => $req->input('sort')];
            $detail = TenantMenu::create($insert);
            // 更新缓存
            app('com')->updateCache(new TenantMenu());
            DB::commit();
            return $this->resData(200, '添加权限菜单成功...', $detail);
        } catch (\Throwable $e) {
            DB::rollback();
            return $this->resData(500, '添加权限菜单失败，请稍后再试...');
        }
    }
    // 修改菜单
    public function postEdit(Request $req)
    {
        DB::beginTransaction();
        try {
            $validator = Validator::make($req->input(), [
                'parentid' => 'integer',
                'id' => 'required|integer',
                'name' => 'required|max:255',
                'url' => 'required|max:255',
                'label' => 'required|max:255',
                'display' => 'required|in:true,false',
            ]);
            $attrs = array(
                'parentid' => '父菜单',
                'id' => '菜单ID',
                'name' => '菜单名称',
                'url' => '菜单名称',
                'label' => '菜单标签',
                'display' => '状态',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $req->input('id');
            $update = ['parentid' => $req->input('parentid', 0), 'name' => $req->input('name'), 'url' => $req->input('url'), 'label' => $req->input('label'), 'icon' => $req->input('icon'), 'display' => $req->input('display') == 'true' ? 1 : 0, 'sort' => $req->input('sort')];
            TenantMenu::where('id', $id)->update($update);
            // 更新缓存
            app('com')->updateCache(new TenantMenu());
            DB::commit();
            return $this->resData(200, '更新权限菜单成功...');
        } catch (\Throwable $e) {
            DB::rollback();
            return $this->resData(500, '更新权限菜单失败，请稍后再试...');
        }
    }
    // 取单条信息
    public function postDetail(Request $req)
    {
        try {
            $validator = Validator::make($req->input(), [
                'menu_id' => 'required|integer',
            ]);
            $attrs = array(
                'menu_id' => '菜单ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $menu_id = $req->input('menu_id');
            $detail = TenantMenu::findOrFail($menu_id);
            return $this->resData(200, '获取成功...', $detail);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取失败，请稍后再试...');
        }
    }
    // 取单条信息
    public function postSort(Request $req)
    {
        try {
            $validator = Validator::make($req->input(), [
                'menu_id' => 'required|integer',
                'sort' => 'required|integer',
            ]);
            $attrs = array(
                'menu_id' => '菜单ID',
                'sort' => '排序',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $menu_id = $req->input('menu_id');
            $sort = $req->input('sort');
            TenantMenu::where('id', $menu_id)->update(['sort' => $sort]);
            return $this->resData(200, '排序成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '排序失败，请稍后再试...');
        }
    }
    // 删除一条，同时删除子菜单
    public function postRemove(Request $req)
    {
        DB::beginTransaction();
        try {
            $validator = Validator::make($req->input(), [
                'menu_id' => 'required|integer',
            ]);
            $attrs = array(
                'menu_id' => '菜单ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $menu_id = $req->input('menu_id');
            $info = TenantMenu::findOrFail($menu_id);
            $arr = explode(',', $info->arrchildid);
            TenantMenu::destroy($arr);
            // 更新缓存
            app('com')->updateCache(new TenantMenu());
            DB::commit();
            return $this->resData(200, '删除成功...');
        } catch (\Throwable $e) {
            DB::rollback();
            return $this->resData(500, '获取失败，请稍后再试...');
        }
    }
}
